package api

import (
	"blog/models"
	"github.com/astaxie/beego/orm"
	"strconv"
)

type RoleController struct {
	baseController
}

func (r *RoleController) List() {
	page, _ := r.GetInt("page", 1)
	limit, _ := r.GetInt("limit", 25)
	roleList, total, _ := models.GetList(models.RoleTable(), page, limit, orm.NewCondition(), "-Id")
	r.success(roleList, "", total)
}

func (r *RoleController) Create() {
	menu := r.Input()["menu"]
	roleName := r.GetString("role_name")
	role := models.NewRole()
	role.RoleName = roleName
	roleId, err := models.Create(role)
	if err != nil {
		r.error(err.Error())
	}
	for _, k := range menu {
		var roleMenu = models.NewRoleMenu()
		menuId, _ := strconv.Atoi(k)
		roleMenu.MenuId = menuId
		roleMenu.RoleId = int(roleId)
		_, err = models.Create(roleMenu)
		if err != nil {
			r.error(err.Error())
		}
	}
	r.success("")
}

func (r *RoleController) Edit() {
	var roleChan = make(chan bool)
	id, _ := r.GetInt("id", -1)
	menu := r.Input()["menu"]
	roleName := r.GetString("role_name", "")
	if id == -1 {
		r.error("id错误")
	}
	role, err := models.GetById(models.RoleTable(), id)
	if err != nil {
		r.error(err.Error())
	}
	if role["RoleName"] != roleName {
		role["RoleName"] = roleName
		_, _ = models.UpdateByCondition(role)
	}
	go func() {
		_, _ = models.DeleteByCondition(models.RoleMenuTable(), orm.NewCondition().And("role_id", id))
		for _, k := range menu {
			var roleMenu = models.NewRoleMenu()
			menuId, _ := strconv.Atoi(k)
			roleMenu.MenuId = menuId
			roleMenu.RoleId = id
			_, err := models.Create(roleMenu)
			if err != nil {
				r.error(err.Error())
			}
		}
		roleChan <- true
	}()
	<-roleChan
	r.success("")
}

func (r *RoleController) Delete() {
	id, err := r.GetInt64("id")
	if err != nil {
		r.error("传入错误的id")
	}
	if _, err := models.DeleteByCondition(models.RoleTable(), orm.NewCondition().And("id", id)); err != nil {
		r.error(err.Error())
	}
	r.success([]int{})
}
